package genesis.familytree.server.modules.sys.web;

import genesis.familytree.server.common.Constants;
import genesis.familytree.server.common.JsonResult;
import genesis.familytree.server.common.exception.GenesisException;
import genesis.familytree.server.common.persistence.Page;
import genesis.familytree.server.common.security.SystemAuthorizingRealm.Principal;
import genesis.familytree.server.common.web.BaseAdminController;
import genesis.familytree.server.modules.common.entity.Param;
import genesis.familytree.server.modules.common.service.IParamService;
import genesis.familytree.server.modules.sys.entity.SysRole;
import genesis.familytree.server.modules.sys.service.ISysRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

/**
 *
 */
@Controller
@RequestMapping("${familytree.admin-path}/role")
public class SysRoleController extends BaseAdminController {

    @Resource private ISysRoleService roleService;

    /**
     * 后台用户管理主页
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping("/index")
    public Object index() {
        return "redirect:/" + adminPath + "/role/list";
    }

    /**
     * 查看后台用户
     * @return
     */
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public Object viewList() {
        return "/modules/sys/SysRole/SysRole_list";
    }

    @ResponseBody
    @RequiresPermissions("sys:role:view")
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getList(@RequestParam("page") int pageNumber,
                          @RequestParam("rows") int pageSize) {
        JsonResult result = JsonResult.create();

//        int pageSize = Constants.System.DEFAULT_PAGE_SIZE;
        //pageSize = 1;
        Page<SysRole> list = this.roleService.getPage(pageNumber, pageSize, new SysRole());

        result.success("data", list);

        return result;
    }

    @RequiresPermissions("sys:role:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public Object viewCreate(Model model) {

        SysRole entity = new SysRole();
        model.addAttribute("entity", entity);
        return "/modules/sys/SysRole/SysRole_edit";
    }

    @ResponseBody
    @RequiresPermissions("sys:role:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object create(@Valid SysRole role,
                         BindingResult bindingResult,
                         HttpServletRequest request) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }
            if (!beanValidator(result, bindingResult)) {
                return result;
            }

            Date now = new Date();

            int userId = Principal.getCurrent().getId();
            role.setId(null);
            role.setCreateBy(userId);
            role.setCreateDate(now);
            this.roleService.saveOne(role);
        } catch (GenesisException ex) {
            result.error(ex.getMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.error();
        }

        return result;
    }

    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public Object viewUpdate(@RequestParam("id") int roleId,
                             Model model) {

        SysRole byId = this.roleService.getById(roleId);

        model.addAttribute("entity", byId);

        return "/modules/sys/SysRole/SysRole_edit";
    }

    @ResponseBody
    @RequiresPermissions("sys:role:edit")
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object update(@Valid SysRole role,
                         BindingResult bindingResult,
                         HttpServletRequest request) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }
            if (!beanValidator(result, bindingResult)) {
                return result;
            }

            Date now = new Date();

            int userId = Principal.getCurrent().getId();
            role.setUpdateBy(userId);
            role.setUpdateDate(now);
            this.roleService.saveOne(role);
        } catch (GenesisException ex) {
            result.error(ex.getMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.error();
        }

        return result;
    }

    @ResponseBody
    @RequiresPermissions("sys:role:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object delete(@RequestParam("id") int roleId,
                         HttpServletRequest request) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }

            this.roleService.deleteOneById(roleId);
        } catch (GenesisException ex) {
            result.error(ex.getMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.error();
        }

        return result;
    }
}
